code for chartjs in angular js

How to Use ChartJS in AngularJS

Data visualization is an important part of web development and social engine engagement. If you are working on Angular and developing the backend of your next application, then you would need to visualize your data and set it in a way that makes inference and understanding easier.

If you have a data-intensive website, you will find it hard to figure out a way to understand the data. Data visualization methods can help group your data in one place and show it in a way that is easy to understand for all, especially in the form of charts.

AngularJS provides integration with chart js, which is a popular medium for using visualization tools on your data. Technical text filled with jargon can be hard to understand for all your team members, whereas basic charts are not so difficult. Charts can make your website and its data a lot easier to use and can simplify the development process.

In this article, we take a look at how to use ChartJS in AngularJS. This simplified guide will help you in your data collection measures, and give you the means to access complex data with simple tools. Stay with us to learn more:

What Exactly is Chart js?

Chart js is a unique tool on JavaScript, which simplifies data and presents it in a responsive manner. The tool is popular with users because of how it utilizes bar charts, line plots, pie charts, scatter plots, and donut charts for the best visualization methods. Developers can access data and visualize it in a matter of clicks, whereas Chart JS does the major heavy lifting for you.

Chart js is extremely customizable in nature and comes with a definite learning curve. However, we make the process simpler by mentioning how to use chart JS in AngularJS.

How to Use Chart JS in AngularJS

We now look at what you can do to implement Chart JS in AngularJS.

Implement all Chart Data

You need to start by fetching the data for your chart, and using it in a static manner. The chart should be registered with the contractor. The code to follow here is:

import { Component } from '@angular/core';
import { Chart, registerables } from 'chart.js';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'angular-chart';
  constructor() {
    Chart.register(...registerables);
  }
  ngOnInit(): void {
    // Line Chart
    const lineCanvasEle: any = document.getElementById('line_chart')
    const lineChar = new Chart(lineCanvasEle.getContext('2d'), {
      type: 'line',
        data: {
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
          datasets: [
            { data: [12, 15, 18, 14, 11, 19, 12], label: 'Orders', borderColor: 'rgba(54, 162, 235)' },
            { data: [65, 59, 80, 81, 56, 55, 40], label: 'Sales', borderColor: 'rgb(75, 192, 192)' },
          ],
        },
        options: {
          responsive: true,
          scales: {
              y: {
                  beginAtZero: true
              }
          }
        }
      });
    // Bar chart
    const barCanvasEle: any = document.getElementById('bar_chart')
    const barChart = new Chart(barCanvasEle.getContext('2d'), {
      type: 'bar',
        data: {
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
          datasets: [{
            label: 'Sales',
            data: [65, 59, 80, 81, 56, 55, 40],
            backgroundColor: [
              'rgba(255, 99, 132, 0.2)',
              'rgba(255, 159, 64, 0.2)',
              'rgba(255, 205, 86, 0.2)',
              'rgba(75, 192, 192, 0.2)',
              'rgba(54, 162, 235, 0.2)',
              'rgba(153, 102, 255, 0.2)',
              'rgba(201, 203, 207, 0.2)'
            ],
            borderColor: [
              'rgb(255, 99, 132)',
              'rgb(255, 159, 64)',
              'rgb(255, 205, 86)',
              'rgb(75, 192, 192)',
              'rgb(54, 162, 235)',
              'rgb(153, 102, 255)',
              'rgb(201, 203, 207)'
            ],
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          scales: {
              y: {
                  beginAtZero: true
              }
          }
        }
      });
  }
}

Implement the Chart in HTML

The next process in the chain is to implement the chart in HTML. Follow the code below:

<div class="container py-5">
  <div class="row">
    <div class="col-4">
      <canvas id="line_chart" width="400px" height="400px"></canvas>
      <h3 class="text-center mt-3">Line Chart</h3>
    </div>
    <div class="col-4">
      <canvas id="bar_chart" width="400px" height="400px"></canvas>
      <h3 class="text-center mt-3">Bar Chart</h3>
    </div>
  </div>
</div>

Import Module

You can now import the module by adding Chart Module to app.module.ts file:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ChartsModule } from 'ng2-charts';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ChartsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Route all Chart Component

You can now finalize the process by routing all of your Chart component:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BarChartComponent } from './bar-chart/bar-chart.component';
import { BubbleChartComponent } from './bubble-chart/bubble-chart.component';
import { DoughnutChartComponent } from './doughnut-chart/doughnut-chart.component';
import { LineChartComponent } from './line-chart/line-chart.component';
import { PieChartComponent } from './pie-chart/pie-chart.component';
import { PolarChartComponent } from './polar-chart/polar-chart.component';
import { RadarChartComponent } from './radar-chart/radar-chart.component';
import { ScatterChartComponent } from './scatter-chart/scatter-chart.component';
const routes: Routes = [
  {
    path: 'line-chart',
    component: LineChartComponent
  },
  {
    path: 'pie-chart',
    component: PieChartComponent
  },
  {
    path: 'bar-chart',
    component: BarChartComponent
  },
  {
    path: 'doughnut-chart',
    component: DoughnutChartComponent
  },
  {
    path: 'polar-chart',
    component: PolarChartComponent
  },
  {
    path: 'radar-chart',
    component: RadarChartComponent
  },
  {
    path: 'bubble-chart',
    component: BubbleChartComponent
  },
  {
    path: 'scatter-chart',
    component: ScatterChartComponent
  },
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'line-chart'
  }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Chart JS can help make data visualization and chart usage a lot easier on AngularJS. With data being considered to be the fuel that powers your analytics and your website, it is highly necessary that you customize and make visualization models that are easy for all to understand.

The codes and the processes used in this guide will help you create the perfect data visualization model and use Chart JS in AngularJS.

SHARE: